//
//  Pet_CardDetailViewController.swift
//  PetApp
//
//  Created by mac on 2023/9/19.
//  Copyright © 2023 Pet_. All rights reserved.
//

import UIKit

class Pet_CardDetailViewController: BasicViewController,UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate {
    
    private lazy var bannerView: ZAntBannerView = {
        let bannerView = ZAntBannerView(frame: .zero)
        bannerView.clipsToBounds = true
        bannerView.bannerItemSize = CGSize(width: screenWidth, height: 600.Fit)
        return bannerView
    }()
    var model:InfoUtil.room?{
        didSet{
            let arr = self.model?.info2?.components(separatedBy: "@@")
            self.bannerView.imageUrls = arr ?? []
            self.nameL.text = model?.info
            self.timeL.text = model?.info4
            if let url = URL(string: self.model?.icon ?? "") {
                self.avarB.kf.setImage(with: url, for: .normal,placeholder: .init(named: "avarB"))
            }
            self.collectB.isSelected = Pet_CollectManager.shared.CollectList().contains(where: {$0.id == self.model?.id})
            
            self.giftB.setTitle(model?.data1, for: .normal)
            self.descL.text = model?.info1
            coomentDataSource.removeAll()
            if let str = self.model?.info5,str.count != 0 {
                let arr = str.components(separatedBy: "@@")
                for dict in arr{
                    if let d = InfoUtil.commentDta.deserialize(from: dict){
                        coomentDataSource.append(d)
                    }
                }
                self.commentB.setTitle("\(arr.count)", for: .normal)
                self.itemsTableView.reloadData()
            }
            RT.careFriendState(idstring: self.model?.createUserId ?? "") { s in
                self.followB.isSelected = s == "1"
                self.followB.setTitle(self.followB.isSelected ? "Unfollow" : "Follow", for: .normal)
                self.followB.backgroundColor = self.followB.isSelected ? UIColor.color(hexString: "#BBBBBB") : .black
                self.followB.setTitleColor(self.followB.isSelected ? UIColor.color(hexString: "#999999") : mainColor, for: .normal)
            }
            
            RT.fansListAction { info in
                for item in info{
                    if item?.id == self.model?.id {
                        self.collectB.isSelected = true
                    }
                }
            }

        }
    }
    
    let rightB = UIButton.initV(img: "icon_more(3)")
    let backV = UIView.init(frame: .zero)
    let avarB = UIButton.initV(img: "avarB")
    let nameL = UILabel.initV(UIFont.setTypeFace(16,type: .medium), text: "", textColor: .color(hexString: "#666666"))
    let timeL = UILabel.initV(UIFont.setTypeFace(12,type: .medium), text: "", textColor: .color(hexString: "#999999"))
    let descL = UILabel.initV(UIFont.setTypeFace(16,type: .medium), text: "", textColor: titleColor)
    let titleL = UILabel.initV(UIFont.setTypeFace(20,type: .medium), text: "Comment", textColor: titleColor)
    var coomentDataSource:[InfoUtil.commentDta] = []
    private lazy var followB: UIButton = {
        let button = UIButton(type: .custom)
        button.titleLabel?.font = .setTypeFace(16.Fit,type: .medium)
        button.setTitleColor(mainColor, for: .normal)
        button.setTitle("Follow", for: .normal)
        button.backgroundColor = .black
        return button
    }()
    
    private lazy var itemsTableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.delegate = self
        view.dataSource = self
        view.backgroundColor = .clear
        view.register(CommentCell.self, forCellReuseIdentifier: CommentCell.description())
        view.rowHeight = UITableView.automaticDimension
        view.tableHeaderView = self.headerV
        return view
    }()
    
    lazy var headerV: UIView = {
        var h = 750.Fit
        if UIDevice.modelName.contains("iPad") || UIDevice.modelName == "iPhone SE"{
            h = 790.Fit
        }
        let v = UIView.init(frame: .init(x: 0, y: 0, width: screenWidth, height: h))
        v.isUserInteractionEnabled = true
        v.subviews {
            bannerView
            backV.subviews {
                avarB
                followB
                nameL
                timeL
                descL
            }
            titleL
        }
        bannerView.left(0).right(0).top(-NavHeight - 10.Fit).height(600.Fit)
        backV.left(15.Fit).right(15.Fit).height(160.Fit)
        backV.Top == bannerView.Bottom + 20.Fit
        backV.backgroundColor = .white
        backV.setAllCorners(corner: 15.Fit)
        backV.isUserInteractionEnabled = true
        
        avarB.size(45.Fit).left(25.Fit).top(15.Fit)
        avarB.setAllCorners(corner: 22.5.Fit)
        avarB.addAct {
            guard self.model?.createUserId != USEINFOMODEL.id else {
                return
            }
            let vc = Pet_UserinfoViewController()
            vc.userID = self.model?.createUserId
            self.navigationController?.pushViewController(vc, animated: true)
        }
        
        followB.width(80.Fit).height(30).right(25.Fit).top(15.Fit)
        followB.setAllCorners(corner: 15.Fit)
        followB.addAct {
            guard self.model?.createUserId != USEINFOMODEL.id else {
                Toast_View_Tool.show(type: .error,text: "You can't follow yourself")
                return
            }
            Toast_View_Tool.show()
            let type = self.followB.isSelected == true ? "0" : "1"
            RT.AddDeleteFriend(idstring: self.model?.createUserId ?? "", type: type) { s in
                Toast_View_Tool.dismiss()
                self.followB.isSelected = !self.followB.isSelected
                self.followB.setTitle(self.followB.isSelected ? "Unfollow" : "Follow", for: .normal)
                self.followB.backgroundColor = self.followB.isSelected ? UIColor.color(hexString: "#BBBBBB") : .black
                self.followB.setTitleColor(self.followB.isSelected ? UIColor.color(hexString: "#999999") : mainColor, for: .normal)
            }
        }
        
        
        nameL.height(20.Fit).top(15.Fit).right(50.Fit)
        nameL.Leading == avarB.Trailing + 15.Fit
        
        timeL.height(20.Fit).right(50.Fit)
        timeL.Leading == avarB.Trailing + 15.Fit
        timeL.Top == nameL.Bottom
        
        descL.right(15.Fit).left(25.Fit).bottom(10.Fit)
        descL.Top == avarB.Bottom + 5.Fit
        
        titleL.right(15.Fit).left(15.Fit).height(30.Fit)
        titleL.Top == backV.Bottom + 25.Fit
        
        return v
        
    }()
    
    let inputV = UIView.init(frame: .zero)
    let txtfiled1 = UITextField.init(frame: .zero)
    let giftB = UIButton.initV(img: "gitticobn")
    let commentB = UIButton.initV(img: "icon_comment")
    let collectB = UIButton.initV(img: "icon_favorite")

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.setRightItem(rightB)
        rightB.addAct {
            guard self.model?.createUserId != USEINFOMODEL.id else {
                let view = DeleteRoom_View()
                view.deleBlock = {
                    RT.deleteRoom(idstring: self.model?.id ?? "") { s in
                        self.navigationController?.popViewController(animated: true)
                    }
                }
                let page = Pop_Up_Custom_View(config: PopUpViewConfig(view: view, size: CGSize(width: screenWidth-30.Fit, height: 410.Fit)))
                page.isCloseFromClean = false
                page.animatedPop()
                return
            }
            let page = Edit_Choose_Photo_Interface(type: .reportAndBlock(userId: self.model?.createUserId?.intValue ?? 0,personal: false))
            self.present(page, animated: true)
        }
        
        view.subviews {
            itemsTableView
            inputV.subviews {
                txtfiled1
                commentB
                giftB
                collectB
            }
        }
        inputV.backgroundColor = .white
        inputV.left(0).right(0).height(50.Fit + TabbarSafeBottomMargin).bottom(0)
        inputV.isUserInteractionEnabled = true
        
        let attriText = NSMutableAttributedString.init(string: "Say Something")
        attriText.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.color(hexString: "#EBC88C",alpha: 1)], range: NSRange(location: 0, length: attriText.string.count))
        txtfiled1.attributedPlaceholder = attriText
        txtfiled1.textColor = .black
        txtfiled1.backgroundColor = .color(hexString: "#FFF1DA")
        txtfiled1.font = .setTypeFace(15.Fit,type: .medium)
        txtfiled1.setAllCorners(corner: 20.Fit)
        txtfiled1.delegate = self
        txtfiled1.leftView = .init(frame: .init(x: 0, y: 0, width: 20.Fit, height: 20))
        txtfiled1.leftViewMode = .always
        txtfiled1.returnKeyType = .send
        
        collectB.setImage(.init(named: "icon_favorite_on"), for: .selected)
        collectB.top(15.Fit).height(35.Fit).width(35.Fit).right(15.Fit)
                
        commentB.top(15.Fit).height(35.Fit).width(60.Fit)
        commentB.Trailing == collectB.Leading - 10.Fit
        commentB.setTitleColor(.black, for: .normal)
        commentB.titleLabel?.font = .systemFont(ofSize: 14)
        commentB.contentHorizontalAlignment = .leading

        giftB.top(15.Fit).height(35.Fit).width(60.Fit)
        giftB.Trailing == commentB.Leading - 10.Fit
        giftB.contentHorizontalAlignment = .leading
        giftB.setTitleColor(.black, for: .normal)
        giftB.titleLabel?.font = .systemFont(ofSize: 14)
        giftB.addAct {
            let view = GiftSend_View()
            view.sendBlock = {
                RT.buyGiftWith(cost: "20") { info in
                    Toast_View_Tool.show(type: .success,text: "Send Success!")
                    var model1 = self.model!
                    model1.data1 = "\(model1.data1!.intValue + 1)"
                    RT.updateHouse(paraInfo: (model1.toJSON())!) { info in
                        self.model = info
                    }
                }
            }
            let page = Pop_Up_Custom_View(config: PopUpViewConfig(view: view, size: CGSize(width: screenWidth, height: screenHeight)))
            page.isCloseFromClean = false
            page.animatedPop()

        }
        
        txtfiled1.left(15.Fit).width(220.Fit).height(40.Fit).top(15.Fit)
        txtfiled1.Trailing == giftB.Leading - 15.Fit

        
        collectB.addAct {
            self.collectB.isSelected = !self.collectB.isSelected
            if self.collectB.isSelected == true{
                Pet_CollectManager.shared.saveRecord(.init(id: self.model?.id ?? ""))
            }else
            {
                Pet_CollectManager.shared.deleteRecord(.init(id: self.model?.id ?? ""))
            }
        }

        NotificationCenter.default.addObserver(forName: NSNotification.Name("BlockRefreshNotice"), object: nil, queue: nil) {[weak self] noti in
            self?.navigationController?.popViewController(animated: true)
        }

        itemsTableView.left(0).right(0).top(0).height(screenHeight - 55.Fit - TabbarSafeBottomMargin)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        guard self.txtfiled1.text?.isBlank == false else {
            return false
        }
        let date = Date()
        let timeFormatter = DateFormatter()
        timeFormatter.dateFormat = "MM-dd HH:mm"
        let strNowTime = timeFormatter.string(from: date) as String
        let model:InfoUtil.commentDta? = InfoUtil.commentDta.init(headImg: USEINFOMODEL.headImage,name: USEINFOMODEL.name,content: self.txtfiled1.text,time: strNowTime,id:USEINFOMODEL.id,zan:"")
        var arr:[String] = self.model?.info5?.components(separatedBy: "@@") ?? []
        arr.append(model?.toJSONString() ?? "")
        self.model?.info5 = arr.joined(separator: "@@")
        RT.updateHouse(paraInfo: (self.model?.toJSON())!) { info in
            self.model = info
            self.txtfiled1.resignFirstResponder()
            self.txtfiled1.text = ""
            self.itemsTableView.scrollToRow(at: .init(row: self.coomentDataSource.count - 1, section: 0), at: .bottom, animated: false)
        }
        return true
        
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.coomentDataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: CommentCell.description(), for: indexPath) as! CommentCell
        cell.model = self.coomentDataSource[indexPath.row]
        return cell
    }
}


class CommentCell: UITableViewCell {
    
    let headImg = UIImageView.initImgView(img: "avarB")
    let moreB = UIButton.initV(img: "icon_more")
    private var nameL = UILabel.initV(.setTypeFace(16.Fit,type: .system), text: "", textColor:titleColor)
    private var timeL = UILabel.initV(.setTypeFace(14,type: .system), text: "", textColor:.color(hexString: "#666666",alpha: 0.6))
    private var cL = UILabel.initV(.setTypeFace(16,type: .system), text: "", textColor:titleColor)
    
    var model:InfoUtil.commentDta?{
        didSet{
            self.nameL.text = self.model?.name
            self.cL.text = self.model?.content
            if let url = URL(string: self.model?.headImg ?? "") {
                self.headImg.kf.setImage(with: url,placeholder: UIImage.init(named: "avarB"))
            }
            self.timeL.text = self.model?.time
            self.moreB.isHidden = self.model?.id == USEINFOMODEL.id
        }
    }
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        
        contentView.subviews {
            headImg
            moreB
            nameL
            timeL
            cL
        }
        headImg.left(15.Fit).top(5.Fit).size(50.Fit)
        headImg.setAllCorners(corner: 25.Fit)
        
        moreB.size(25.Fit).right(12.Fit)
        moreB.Top == headImg.Top + 10.Fit
        moreB.addAct {
            let view = Report_View()
            view.person = true
            view.reportBlock = { content in
                Toast_View_Tool.show(type: .success,text: "Success!")
            }
            let page = Pop_Up_Custom_View(config: PopUpViewConfig(view: view, size: CGSize(width: screenWidth-30.Fit, height: 415.Fit)))
            page.isCloseFromClean = false
            page.animatedPop()
        }
            
        nameL.height(20.Fit)
        nameL.Leading == headImg.Trailing + 10.Fit
        nameL.CenterY == headImg.CenterY
        nameL.Trailing == moreB.Leading - 10.Fit
        
        cL.bottom(35.Fit).right(25.Fit)
        cL.Top == nameL.Bottom + 10.Fit
        cL.Leading == headImg.Trailing + 10.Fit
        cL.numberOfLines = 0
        
        timeL.height(15.Fit).bottom(10.Fit)
        timeL.Leading == nameL.Leading
        timeL.Trailing == moreB.Leading - 10.Fit

    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
